import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xin_he/page/category/xin_he_category/xin_he_category_view.dart';
import 'package:xin_he/page/category/xin_he_category/xin_he_sub_category/xin_he_sub_category_view.dart';
import 'package:xin_he/page/home/model/xin_he_goods_item_entity.dart';
import 'package:xin_he/page/home/model/xin_he_special_distract_entity.dart';
import 'package:xin_he/page/home/views/xin_he_goods_grid_widget.dart';
import 'package:xin_he/page/shopping_car/models/xin_he_goods_model.dart';
import 'package:xin_he/routes/xin_he_routes.dart';
import 'package:xin_he/utils/xh_styles.dart';
import 'package:xin_he/utils/xin_he_image.dart';

import '../views/xin_he_tab_custom_indicator.dart';
import 'xin_he_home_logic.dart';

class XinHeHomePage extends StatelessWidget {
  XinHeHomePage({Key? key}) : super(key: key);

  final logic = Get.put(XinHeHomeLogic());
  final state = Get.find<XinHeHomeLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Obx(() => Scaffold(
      body: Column(
        children: [

        ///标题栏
        _titleView(),

        ///搜索
        GestureDetector(
            onTap: (){
              Get.toNamed(XinHeRoutes.search);

            },
            child: _searchView()),

        Expanded(
          child: ListView(
            padding: EdgeInsets.zero,
            // mainAxisAlignment: MainAxisAlignment.start,
            children: [



              ///分类tab
              _categoryTabsView(),

              ///banner
              _bannerView(),

              const SizedBox(height: 10.5,),

              ///专区
             state.specialDistrictTabsList.isNotEmpty?  _prefectureView():Container(),

              SizedBox(height:10 ,),

              ///抢购
              // _snapUpView(),


              ///全部 tab
              state.allTabList.isNotEmpty? _bottomTabsView():Container(),

              ///全部 items
            state.allTabList.isNotEmpty&&state.allTabDataList.isNotEmpty?  _bottomItemListView(): Container( alignment:Alignment.center,height: 200, child: const Text('暂无数据')),

            ],
          ),
        )
      ],),
    ));
  }

  Widget _titleView() {
    return Stack(children: [
      Container(
        color: XinHeStyle.mainGreenColor,
        width: Get.width,
        height: Get.mediaQuery.padding.top+64,
        padding: EdgeInsets.only(left: 15),
        alignment: Alignment.centerLeft,
        child: const Text('芯禾玉品',style: TextStyle(color: Colors.white,fontSize: 17,fontWeight: FontWeight.w600),),
      ),

      Positioned(
        bottom: 0,
        child: Container(
          height: 18,
          width: Get.width,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(topLeft: Radius.circular(15),topRight: Radius.circular(15)),

          ),
        ),
      )
    ],);
  }

  Widget _searchView() {
    return Container(
        color: Colors.white,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              height: 33,
              margin: const EdgeInsets.symmetric(horizontal: 15),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(16.5),
                  border: Border.all(width: 1,color:XinHeStyle.mainGreenColor )
              ),
              child: Row(
                children: [
                  const Padding(
                    padding: EdgeInsets.only(left: 10,right: 5),
                    child: XinHeAssetImage('assets/images/home/search_12.png',width: 12,height: 12,fit: BoxFit.fill,),
                  ),
                  Text('请输入关键字',style: TextStyle(color: XinHeColor('#B1B1B1'),fontSize: 13),),
                  const Spacer(),
                  Container(
                    width: 54,
                    height: 33,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: XinHeStyle.mainGreenColor,
                      borderRadius: BorderRadius.circular(16.5),
                    ),
                    child: const Text('搜索',style: TextStyle(color: Colors.white,fontSize: 13),),
                  ),

                ],
              ),
            ),
            SizedBox(height: 5,)
        ],));
  }

  Widget _categoryTabsView() {
    return Container(
      color: Colors.white,
      width: Get.width,
      height: 11+28+22.5+15,
      padding: const EdgeInsets.only(left: 15,top: 11,right: 15),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        padding: const EdgeInsets.symmetric(horizontal: 0),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 5,
          mainAxisSpacing: 22,
          crossAxisSpacing: 0,
          // childAspectRatio: 163.5/200.0
        ),
        itemBuilder: (ctx,index){
          return GestureDetector(
            onTap: (){
              var timeNumber = DateTime.now().millisecondsSinceEpoch;
              String st = "$timeNumber";
              Get.to(XinHeSubCategoryPage(tag: st,),arguments: index,preventDuplicates: false);
            },
            child: Container(
              color: Colors.white,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [

                  XinHeAssetImage('assets/images/home/${logic.categoryIconList[index]}.png',width: 28,height: 28,fit: BoxFit.fill,),

                  Container(
                    alignment: Alignment.center,
                    height: 22.5,
                    child: Text(logic.categoryTitleList[index],style: TextStyle(fontSize: 13,color: XinHeColor('##2B3131'),fontWeight: FontWeight.w500)),
                  ),
                  const SizedBox(height: 15,)
                ],),
            ),
          );
        },
        itemCount: 5,
      ),
    );
  }

  Widget _bannerView() {
    return Container(
        width: double.infinity,
        height: 142,
        margin: const EdgeInsets.only(
            left: 15,right: 15, top: 0),
        decoration: const BoxDecoration(
            color: Colors.transparent),
        clipBehavior: Clip.hardEdge,
        child: logic.bannerList.isNotEmpty
            ? Obx(() => Swiper(
          loop: true,
          autoplay: true,
          physics: const ClampingScrollPhysics(),
          itemCount: logic.bannerList.length,
          scrollDirection: Axis.horizontal,
          pagination: SwiperCustomPagination(builder:
              (BuildContext context,
              SwiperPluginConfig? config) {
            return Container(
                width: double.infinity,
                alignment: Alignment.bottomCenter,
                padding: const EdgeInsets.only(
                    right: 12, bottom: 10),
                child: Row(
                  mainAxisAlignment:
                  MainAxisAlignment.center,
                  crossAxisAlignment:
                  CrossAxisAlignment.center,
                  mainAxisSize: MainAxisSize.min,
                  children: logic.bannerList
                      .asMap()
                      .keys
                      .map((index) {
                    bool isActive = index ==
                        (config?.activeIndex ?? 0);
                    return Container(
                      margin:
                      const EdgeInsets.only(left: 4),
                      width: 6,
                      decoration: BoxDecoration(
                          color: isActive
                              ? Colors.white
                              : const Color.fromRGBO(
                              255, 255, 255, 0.7),
                          borderRadius:
                          BorderRadius.circular(3)),
                      height: 6,

                    );
                  }).toList(),
                ));
          }),
          itemBuilder: (context, index) {
            final cHomeBannerModel = logic.bannerList[index];
            return GestureDetector(
              onTap: () {
              },
              child: Stack(
                children: [
                  CachedNetworkImage(
                      imageUrl: cHomeBannerModel.imgUrl,
                      placeholder: (context, url) =>
                          Image.asset(
                            'assets/images/home/home_pic_default.png',
                            cacheHeight: 300,
                            cacheWidth:
                            (Get.width - 32).toInt()*2,
                            fit: BoxFit.cover,
                          ),
                      height: 150,
                      width: Get.width - 32,
                      memCacheHeight: 300,
                      memCacheWidth:
                      (Get.width - 32).toInt() * 2,
                      cacheKey: cHomeBannerModel.imgUrl,
                      fit: BoxFit.cover,
                      errorWidget: (context, url, error) {
                        return Image.asset(
                          'assets/images/home/home_pic_default.png',
                          cacheHeight: 300,
                          cacheWidth:
                          (Get.width - 32).toInt()*2,
                          fit: BoxFit.cover,
                        );
                      }),
                ],
              ),
            );
          },
          onTap: (index) {
          },
        ))
            : const XinHeAssetImage('assets/images/home/banner_default.png',fit: BoxFit.fill,)
    );
  }

///专区
  Widget _prefectureView(){
    return Container(
      width: double.infinity,
      height: 227,
      margin: const EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(
          color: Colors.white,borderRadius: BorderRadius.circular(5)
      ),
      child: Column(
        children: [
          ///tabs
          Container(
            height: 47,
            color: Colors.white,
            child: TabBar(
                onTap: (index){
                    XinHeSpecialDistractEntity model = state.specialDistrictTabsList[index];
                    logic.requestSpecialDistritData(model.id);
                },
                controller: logic.tabController,
                labelColor: XinHeColor('#2B3131'),
                unselectedLabelColor: XinHeColor('#909696'),
                labelStyle: const TextStyle(fontSize: 15,fontWeight: FontWeight.w600 ),
                unselectedLabelStyle: const TextStyle(fontSize: 13,fontWeight: FontWeight.w400 ),
                // indicatorColor: XinHeStyle.mainGreenColor,
                indicator: RoundedTabIndicator(width: 29,height: 2),
                indicatorPadding: const EdgeInsets.only(top: 10),
                tabs: state.specialDistrictTabsList.map((e) => Container(
                  height: 47,
                  alignment: Alignment.center,
                  child: Text(e.name??'',softWrap: false,),
                )).toList()

            ),
          ),

          ///items 列表
          Container(
            height: 180,
            width: Get.width-30,
            padding: const EdgeInsets.only(left: 10),
            child: state.specialDistrictTabsDetailList.isNotEmpty? GridView.builder(
              shrinkWrap: true,
              padding: const EdgeInsets.symmetric(horizontal: 0),
              scrollDirection: Axis.horizontal,
              gridDelegate:  const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 1,
                  mainAxisSpacing: 10,
                  childAspectRatio: 2
              ),
              itemBuilder: (ctx,index){
                XinHeGoodsItemEntity model = state.specialDistrictTabsDetailList[index];

                return GestureDetector(
                  onTap: (){
                    Get.toNamed(XinHeRoutes.goodsDetail,arguments: model.id);
                  },
                  child: _prefectureItemView(model,),
                );
              },
              itemCount: state.specialDistrictTabsDetailList.length,
            ):const Center(child: Text('暂无数据')),
          ),



        ],
      ),
    );
  }
  Widget _prefectureItemView(XinHeGoodsItemEntity model) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [

          Container(
            width: 90,
            height: 90,
            decoration: BoxDecoration(
              color: Colors.transparent,
              borderRadius: BorderRadius.circular(5),
            ),
            child:  XinHeNetImage(url: model.iconPath??'',placeholderUrl: 'assets/images/home/tmp.png',),
          ),

          const SizedBox(height: 4,),
          Container(
            alignment: Alignment.centerLeft,
            height: 23,
            // padding: const EdgeInsets.symmetric(horizontal: 4),
            child: Text(
              model.name!.replaceAll("", "\u{200B}"),
              style: TextStyle(fontSize: 13,color: XinHeColor('#2B3131')),
              softWrap: false,
              overflow: TextOverflow.ellipsis,
            ),
          ),

          ///  价格
          Container(
            height: 63,
            // color: Colors.blue,
            alignment: Alignment.centerLeft,
            child: Row(
              children: [
                Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    RichText(
                        text: TextSpan(children: [
                          ///￥
                          TextSpan(
                            text: '￥',
                            style: TextStyle(
                              color: XinHeColor('#E84128'),
                              fontSize: 9,
                              fontWeight: FontWeight.w500,
                            ),
                          ),

                          ///
                          TextSpan(
                            text: '${model.price??''}',
                            style: TextStyle(
                              color: XinHeColor('#E84128'),
                              fontSize: 16,
                              fontWeight: FontWeight.w500,
                            ),
                          ),

                        ]
                        )),

                    Container(
                        height: 18,
                        padding: EdgeInsets.only(left: 4),
                        alignment: Alignment.centerLeft,
                        child: Text('¥${model.originalPrice??''}',style: TextStyle(color: XinHeColor('#B2B2B2'),fontWeight: FontWeight.w500,fontSize: 11,decoration: TextDecoration.lineThrough),)
                    )
                  ],
                ),
                Spacer(),

                // GestureDetector(
                //   onTap: (){
                //     logic.addGoodsToCartAction(XinHeGoodsModel());
                //   },
                //   child: Padding(
                //     padding: const EdgeInsets.only(left: 8),
                //     child: XinHeAssetImage('assets/images/home/add.png',width: 22,height: 22,),
                //   ),
                // )
              ],
            ),
          )
        ],
      ),
    );
  }
  Widget _snapUpView(){
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 15),
      height: (Get.width-30-10)*0.5*166.85/167.5,
      color: Colors.transparent,
      child: Row(
        children: [
          ///限时抢购
          GestureDetector(
            onTap: (){
              Get.toNamed(XinHeRoutes.flashSale);
            },
            child: Container(
              width: (Get.width-30-10)*0.5,
              padding: EdgeInsets.symmetric(horizontal: 9),
              decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(5)),
              child: Column(children: [
                SizedBox(height: 13.5,),
                Container(
                  height: 18,
                  // color: Colors.blue,
                  child: Row(children: [

                    Container(
                        height:18,
                        alignment: Alignment.center,
                        child: Text('限时抢购',style: TextStyle(color: XinHeColor('#222222'),fontSize: 14,fontWeight: FontWeight.w600),strutStyle: StrutStyle(fontSize: 14,forceStrutHeight: true),)),

                    Spacer(),

                    ///倒计时
                    Obx(() => Container(
                      width: 16*3+19,
                      height: 16,
                      child: Row(
                        children: [
                          Container(
                            width:16,
                            decoration: BoxDecoration(color: XinHeColor('#FE8C0F'),borderRadius: BorderRadius.circular(2)),
                            alignment: Alignment.center,
                            child: Text(logic.snapUpHour.value,style: TextStyle(color: Colors.white,fontSize: 12,fontWeight: FontWeight.w500),),
                          ),
                          Container(
                            width: 9.5,
                            alignment: Alignment.center,
                            child: Text(':',style: TextStyle(color: XinHeColor('#FE8C0F'),fontSize: 12,fontWeight: FontWeight.w500),),
                          ),
                          Container(
                            width:16,
                            decoration: BoxDecoration(color: XinHeColor('#FE8C0F'),borderRadius: BorderRadius.circular(2)),
                            alignment: Alignment.center,
                            child: Text(logic.snapUpMinute.value,style: TextStyle(color: Colors.white,fontSize: 12,fontWeight: FontWeight.w500),),
                          ),
                          Container(
                            width: 9.5,
                            alignment: Alignment.center,
                            child: Text(':',style: TextStyle(color: XinHeColor('#FE8C0F'),fontSize: 12,fontWeight: FontWeight.w500),),
                          ),
                          Container(
                            width:16,
                            decoration: BoxDecoration(color: XinHeColor('#FE8C0F'),borderRadius: BorderRadius.circular(2)),
                            alignment: Alignment.center,
                            child: Text(logic.snapUpSecond.value,style: TextStyle(color: Colors.white,fontSize: 12,fontWeight: FontWeight.w500),),
                          ),
                        ],),
                    ))


                  ],),
                ),

                SizedBox(height: 7.5,),


                ///列表
                GridView.builder(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  padding: const EdgeInsets.symmetric(horizontal: 0),
                  scrollDirection: Axis.vertical,
                  gridDelegate:  const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      mainAxisSpacing: 0,
                      crossAxisSpacing: 9.5,
                      childAspectRatio: 70.5/129
                  ),
                  itemBuilder: (ctx,index){
                    return GestureDetector(
                      onTap: (){
                        Get.toNamed(XinHeRoutes.flashSaleDetail);
                      },
                      child: _snapUpItemView(),
                    );
                  },
                  itemCount: 2,
                )


              ],
              ),
            ),
          ),

          SizedBox(width: 9.5,),

          ///特价团购
          GestureDetector(
            onTap: (){
              Get.toNamed(XinHeRoutes.groupPurchase);
            },
            child: Container(
              width: (Get.width-30-10)*0.5,
              padding: const EdgeInsets.symmetric(horizontal: 9),
              decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(5)),
              child: Column(children: [
                SizedBox(height: 13.5,),
                Container(
                  height: 18,
                  // color: Colors.blue,
                  child: Row(children: [

                    Container(
                        height:18,
                        alignment: Alignment.center,
                        child: Text('特价团购',style: TextStyle(color: XinHeColor('#222222'),fontSize: 14,fontWeight: FontWeight.w600),strutStyle: StrutStyle(fontSize: 14,forceStrutHeight: true),)),

                    Spacer(),

                    Container(
                      width: 16*3+19,
                      height: 16,
                      child: Text('623人正在拼',style: TextStyle(color: XinHeColor('#FE8C0F'),fontSize: 12,fontWeight: FontWeight.w600),),
                    )


                  ],),
                ),

                SizedBox(height: 7.5,),


                ///列表
                GridView.builder(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  padding: const EdgeInsets.symmetric(horizontal: 0),
                  scrollDirection: Axis.vertical,
                  gridDelegate:  const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      mainAxisSpacing: 0,
                      crossAxisSpacing: 9.5,
                      childAspectRatio: 70.5/129
                  ),
                  itemBuilder: (ctx,index){
                    return GestureDetector(
                      onTap: (){
                        Get.toNamed(XinHeRoutes.groupPurchaseDetail);
                      },
                      child: _snapUpItemView(),
                    );
                  },
                  itemCount: 2,
                )


              ],
              ),
            ),
          ),




        ],
      ),
    );
  }

  ///限时抢购 与特价团购 item
  Widget _snapUpItemView() {

    return Container(
      color: Colors.white,
      child: Column(
        children: [

          Container(
            // width: (Get.width-30-10)*0.5,
            // height: (Get.width-30-10)*0.5,
            decoration: BoxDecoration(
              color: Colors.yellow,
              borderRadius: BorderRadius.circular(5),
            ),
            child: XinHeAssetImage('assets/images/home/tmp.png',fit: BoxFit.fill,),
          ),

          const SizedBox(height: 10.5,),

          ///当前价格
          Container(
            height: 19,
            margin: const EdgeInsets.symmetric(horizontal: 4),
            alignment: Alignment.center,
            decoration: BoxDecoration(border: Border.all(color: XinHeColor('#E84128'),width: 0.5),borderRadius: BorderRadius.circular(9.5)),
            child: RichText(
                text: TextSpan(children: [
                  ///￥
                  TextSpan(
                    text: '￥',
                    style: TextStyle(
                      color: XinHeColor('#E84128'),
                      fontSize: 9,
                      fontWeight: FontWeight.w500,
                    ),
                  ),

                  ///
                  TextSpan(
                    text: '28.8',
                    style: TextStyle(
                      color: XinHeColor('#E84128'),
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    ),
                  ),


                ]
                )),),

          ///原始价格
          Container(
              height: 18,
              alignment: Alignment.center,
              child: Text('¥38.99',style: TextStyle(color: XinHeColor('#B2B2B2'),fontWeight: FontWeight.w500,fontSize: 11,decoration: TextDecoration.lineThrough),)
          ),
          // Container(height: 11,color: Colors.green,)

        ],
      ),
    );
 }

  Widget _bottomTabsView() {
    return  Container(
      height: 44,
      color: XinHeStyle.defaultBgColor,
      margin: const EdgeInsets.symmetric(horizontal: 15),
      child: TabBar(
          onTap: (index){
            XinHeSpecialDistractEntity model = state.allTabList[index];
            logic.requestAllTabsDataItem(model.id);
          },
          isScrollable: true,
          controller: logic.categoryTabController,
          labelColor: XinHeColor('#2B3131'),
          unselectedLabelColor: XinHeColor('#909696'),
          labelStyle: const TextStyle(fontSize: 15,fontWeight: FontWeight.w600 ),
          unselectedLabelStyle: const TextStyle(fontSize: 13,fontWeight: FontWeight.w400 ),
          indicator: RoundedTabIndicator(width: 29,height: 2),
          indicatorPadding: const EdgeInsets.only(top: 10),
          // labelPadding: EdgeInsets.symmetric(horizontal: logic.getPaddingWidth()) ,
          labelPadding: const EdgeInsets.symmetric(horizontal: 20),

          tabs: state.allTabList.map((e) => Container(
            height: 44,
            alignment: Alignment.center,
            child: Text(e.name,softWrap: false,),
          )).toList()

      ),
    );
  }

  Widget _bottomItemListView(){
    return Container(
      width: Get.width-30,
      padding: const EdgeInsets.only(left: 15,right: 15),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        padding: const EdgeInsets.symmetric(horizontal: 0),
        scrollDirection: Axis.vertical,
        gridDelegate:  const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            mainAxisSpacing: 9.5,
            crossAxisSpacing: 10.5,
            childAspectRatio: 167.5/255.5
        ),
        itemBuilder: (ctx,index){
          XinHeGoodsItemEntity model = state.allTabDataList[index];
          return GestureDetector(
            onTap: (){
              Get.toNamed(XinHeRoutes.goodsDetail,arguments: model.id);
            },
            child: XinHeGoodsGridWidget(model: model,onTapCallback: (){
              logic.addGoodsToCartAction(XinHeGoodsModel());
            },),
          );
        },
        itemCount: state.allTabDataList.length,
      ),
    );
  }
}
